package com.rtx.wms.std.handler.transfer.mid;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.wms.std.ctclass.ClassHolder;
import com.rtx.wms.std.so.bean.Orderdetail;
import com.rtx.wms.std.so.bean.Orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.model.base.Constant;
import com.rtx.model.emums.SysNumberType;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.common.service.CommonService;
import com.rtx.wms.std.transer.bean.ApiTransfer;
import com.rtx.wms.std.transer.bean.ApiTransferdetail;
import com.rtx.wms.std.transer.bean.Transfer;
import com.rtx.wms.std.transer.bean.TransferDetail;
import com.rtx.wms.std.transer.service.ApiTransferService;
import com.rtx.wms.std.transer.service.TransferService;

import cn.hutool.core.util.StrUtil;

/**
 * 内部转移单中间表
 */
@Component
public class MidTransferHandler {
	
    private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	ApiTransferService apiTransferService;
	
    @Autowired
    private CommonService commonService;
    
    @Autowired
    TransferService transferService;
    
    /**
     * 出库单从中间表写入WMS
     * @param whseid
     */
    public void handlerMidToWms(String whseid, ApiMappingInfoBo bo){
        //获取中间表未处理成功的订单
        List<ApiTransfer> list = selectApidata("ris_edi",bo);
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        for(ApiTransfer o : list){
            //添加wms出库单
            addWms(whseid,o,bo);
            //更新中间表状态
            updateStatus("ris_edi",o);
        }
    }
    
    //获取待处理单据
    protected List<ApiTransfer> selectApidata(String datasourcekey,ApiMappingInfoBo bo) {
        QueryWrapper<ApiTransfer> qw = Wrappers.query();
    	qw.in("ediflag", Constant.DEFAULT_FLAG,Constant.FAIL_FLAG);
    	qw.lt("rtxqueue", Constant.DEFAULT_COUNT);
    	return apiTransferService.queryWithDetailByCondition(datasourcekey, qw,bo);
    };
    
    
    //写入wms
    protected void addWms(String datasourcekey,ApiTransfer t,ApiMappingInfoBo bo) {
        try {
        	LambdaQueryWrapper<Transfer> query = Wrappers.lambdaQuery();
        	query.eq(Transfer::getRtxexternkey, t.getRtxexternkey());
        	List<Transfer> list =	transferService.queryByCondition(t.getWhseid(), query);
        	if(list != null && list.size() > 0) {
        		throw new RuntimeException("单据"+t.getRtxexternkey()+"，已进行仓库作业，无无法修改");
        	}

        	Transfer orders = convertTransfer(t.getWhseid(),t,bo);
            //新增出库单
        	transferService.insertTrnsferAndDetail(datasourcekey, orders);

            t.setEdiflag(WmsConstant.SUCCESS_FLAG);
            t.setCallristransferflag(WmsConstant.DEFAULT_FLAG);
        } catch (Exception e) {
            logger.error("仓库{}，批次号{}从中间表写入WMS异常",t.getWhseid(),t.getBatchid(),e);
            t.setEdiflag(WmsConstant.FAIL_FLAG);
            t.setEdimsg(e.getMessage());
        }
    }
    
    /**
     * 转化类型
     * @param o
     * @return
     */
    protected Transfer convertTransfer(String whseid,ApiTransfer at,ApiMappingInfoBo bo) {
        //获取wms单号
        String transferkey = commonService.getWmsKey(whseid, SysNumberType.SysNumberType11);
        at.setTransferkey(transferkey);
        Transfer t = createTransfer(bo);
        BeanUtils.copyProperties(at,t,"serialkey","details");
        t.setTransferkey(transferkey);
        t.setRtxexternkey(at.getRtxexternkey());
        t.setExterntransferkey(at.getRtxexternkey());
        t.setFromstorerkey(at.getStorerkey());
        t.setTostorerkey(at.getStorerkey());
        t.setType("LOT");
        t.setRtxerptype(at.getRtxErptype());
        t.setRtx_erptype(at.getRtxErptype());
        t.setNotes(at.getNotes());
        t.setStatus("0");
        t.setWhseid(at.getWhseid().toUpperCase());
        t.setToexamine(at.getToexamine());
        t.setAdddate(new Date());
        t.setEditdate(new Date());
        int totalline = 0;;
        Double totalQty = 0D;
       
        List<TransferDetail> tdList = new ArrayList<TransferDetail>();
        int line = 1;
        for(ApiTransferdetail atd : at.getDetails()){
        	TransferDetail detail = createTransferDetail(bo);
            BeanUtils.copyProperties(atd,detail,"serialkey");
            detail.setStatus("0");
            totalQty += Double.parseDouble(atd.getQty());
            totalline++;
            detail.setExterntransferkey(at.getRtxexternkey());
            detail.setTransferkey(transferkey);
            detail.setTransferlinenumber(String.format("%05d", line++));
            detail.setRtxexternlineno(atd.getRtxexternlineno());
            detail.setFromsku(atd.getFromsku());
            detail.setFromqty(atd.getQty());
            detail.setRtxuom(atd.getRtxuom());
            detail.setSku(atd.getFromsku());
            detail.setTosku(atd.getFromsku());
            detail.setToqty(atd.getQty());
            detail.setAdddate(new Date());
            detail.setEditdate(new Date());
            
            tdList.add(detail);
           }
        t.setTotallines(totalline+"");
        t.setOpenqty(totalQty+"");  
        
        t.setDetails(tdList);
        return t;
    }

    public Transfer createTransfer(ApiMappingInfoBo config){
        Transfer head = null;
        try {
            Long apiid =  config.getTargetApi().getId();
            Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid+"");
            if(map != null) {
                Class headclass =map.get("main_link");
                head = (Transfer) headclass.newInstance();
            }else {
                head = new Transfer();
            }
        } catch (Exception e) {
            head = new Transfer();
        }

        return head;
    }

    public TransferDetail createTransferDetail(ApiMappingInfoBo config){
        TransferDetail head = null;
        try {
            Long apiid =  config.getTargetApi().getId();
            Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid+"");
            if(map != null) {
                Class headclass =map.get("sub_link");
                head = (TransferDetail) headclass.newInstance();
            }else {
                head = new TransferDetail();
            }
        } catch (Exception e) {
            head = new TransferDetail();
        }

        return head;
    }
    
    /**
     * 更新中间表
     * @param whseid
     * @param apiOrders
     */
    private void updateStatus(String whseid,ApiTransfer at) {
        LambdaUpdateWrapper<ApiTransfer> update = Wrappers.lambdaUpdate();
        update.eq(ApiTransfer::getSerialkey,at.getSerialkey())
        		.set(StringUtils.hasText(at.getTransferkey()), ApiTransfer::getTransferkey,at.getTransferkey())
                .set(StringUtils.hasText(at.getCallristransferflag()),ApiTransfer::getCallristransferflag,at.getCallristransferflag())
        		.set(ApiTransfer::getEdiflag,at.getEdiflag())
                .set(StringUtils.hasText(at.getEdimsg()),ApiTransfer::getEdimsg,StrUtil.sub(at.getEdimsg(),0,200))
                .set(ApiTransfer::getRtxqueue,at.getRtxqueue() + 1);
        apiTransferService.updApiTransferStatus(whseid, update);
    }
}
